#include "LaserDispatcher.h"

#include <stdio.h>
#include <time.h>

LaserDispatcher::LaserDispatcher(LaserFinder* lf):
					lf(lf),
					empty_count_treshold(20) {
}

LaserDispatcher::LaserDispatcher(LaserFinder* lf, unsigned emptyCountTreshold):
					lf(lf),
					empty_count_treshold(emptyCountTreshold) {
}


void LaserDispatcher::notifyListeners() const {
	set<LaserListener*>::const_iterator it;
	for (it = listeners.begin(); it != listeners.end(); it++) {
		printf("notify listener\n");
		if (current_event.type == LASER_INTERVAL) {
			(*it)->isInterval(current_event);
		} else if (current_event.type == LASER_TRACK) {
			(*it)->isTrack(current_event);
		}
	}
}

bool LaserDispatcher::addListener(LaserListener* l) {
	return (listeners.insert(l)).second;
}

void LaserDispatcher::start() {
	finished = true;
	empty_count = 0;
	Track & track = current_event.track;
	clock_t trackEnd = clock();
	unsigned trackCount = 0;
	while(true) {
		IplImage* img = lf->getImage();
		if(!img) {
			break;
		}
		int x = 0;
		int y = 0;
		if (lf->getPoint(img, &x, &y)){
			if (finished) {
				//empty_count = 0;
				track.clear();
				finished = false;
				current_event.time = unsigned(clock() - trackEnd);
				current_event.x = x;
				current_event.x = y;
				current_event.type = LASER_INTERVAL;
				notifyListeners();
			}
			track.addPoint(x, y);
			printf("%d x %d\n", x, y);
		} else {
			//printf("empty\n");
			empty_count++;
			if (!finished && lf->getEmptyCounter() > empty_count_treshold) {
				finished = true;
				current_event.type = LASER_TRACK;
				printf("track #%u finished\n", trackCount);
				trackCount++;
				notifyListeners();
				trackEnd = clock();
				empty_count = 0;
			}
		}
	}
}
